# coding:utf-8
from ctypes import windll
from datetime import datetime
from pathlib import Path

from PyQt5.QtCore import Qt
from PyQt5.QtGui import QResizeEvent, QIcon, QKeyEvent
from PyQt5.QtWidgets import QVBoxLayout, QToolButton, QFileDialog, QListWidgetItem, QWidget, QAbstractItemView
from .image_tools import TopToolsView, BottomToolsView, PictureDetailsDialog, ImagePager
from .image_viewer import ImageGraphicsView
from send2trash import send2trash
from tools import getStyleSheetFromFile
from config import picture_type
import res.res_rc


class ImageView(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.imageList = []
        self.imagePos = 0

        self.graphicsView = ImageGraphicsView(parent=self)
        self.topToolsView = TopToolsView(self)
        self.topToolsView.setObjectName("topToolsView")
        self.bottomToolsView = BottomToolsView(self)
        self.bottomToolsView.setObjectName("bottomToolsView")
        self.imagePager = ImagePager(self)
        self.imagePager.hide()

        self.nextButton = QToolButton(self)
        self.lowerButton = QToolButton(self)
        self.__initLayout()
        self.__initEvent()
        self.setQss()

        self.NextAndLowerButtonHideOrShow()

    def __initEvent(self):
        self.nextButton.setText('下一页')
        self.nextButton.setToolTip('下一页')
        self.lowerButton.setText('上一页')
        self.lowerButton.setToolTip('上一页')

        self.nextButton.clicked.connect(self.on_nextButton_clicked)
        self.lowerButton.clicked.connect(self.on_lowerButton_clicked)

        self.topToolsView.detailed.connect(self.on_detailed_clicked)
        self.topToolsView.rotationed.connect(lambda: self.graphicsView.rotateClockwise())
        self.topToolsView.setWallpapered.connect(self.on_setWallpapered_clicked)
        self.topToolsView.saveAsed.connect(self.on_saveAsed_clicked)
        self.topToolsView.deleted.connect(self.on_deleted_clicked)

        self.bottomToolsView.added.connect(self.on_added_clicked)
        self.bottomToolsView.menued.connect(self.on_bottomToolsView_menued_clicked)
        self.bottomToolsView.enlarged.connect(self.graphicsView.enlargePicture)
        self.bottomToolsView.shrinked.connect(self.graphicsView.shrinkPicture)
        self.bottomToolsView.scaleToFited.connect(self.graphicsView.setAdaptation)
        self.bottomToolsView.actualed.connect(self.graphicsView.setOriginalSize)
        self.bottomToolsView.fullScreened.connect(self.on_fullScreened_clicked)

        self.imagePager.currentItemChanged.connect(self.on_imagePager_currentItemChanged)

    def __initLayout(self):
        self.vBox = QVBoxLayout(self)
        self.vBox.setContentsMargins(0, 0, 0, 0)
        self.vBox.setSpacing(0)

        self.vBox.addWidget(self.topToolsView)
        self.vBox.addWidget(self.graphicsView)
        self.vBox.addWidget(self.imagePager)
        self.vBox.addWidget(self.bottomToolsView)

        self.nextButton.setFixedWidth(50)
        self.lowerButton.setFixedWidth(50)

        self.lowerButton.move(self.graphicsView.pos())

        self.nextButton.setIcon(QIcon(':/svg/svg/CareRightSolid_black.svg'))
        self.lowerButton.setIcon(QIcon(':/svg/svg/CareLeftSolid_black.svg'))

    def setImage(self, file):
        if Path(file).suffix not in picture_type:
            return

        # 每次打开文件时初始化数据列表
        self.imagePager.clear()
        self.imageList = []

        fileName = Path(file).absolute()
        if not fileName.is_file():
            return

        for i in fileName.parent.glob('*'):
            path = Path(i).absolute()
            if path.suffix in picture_type:
                self.imageList.append(str(path))

        self.imagePos = self.imageList.index(str(fileName))
        self.imagePager.addImages(self.imageList)
        self.imagePager.setCurrentRow(self.imagePos)
        self.imagePager.scrollToItem(self.imagePager.item(self.imagePos), QAbstractItemView.PositionAtCenter)
        self.imagePager.setImagePos(self.imagePos)

        self.graphicsView.setImage(str(fileName))
        self.NextAndLowerButtonHideOrShow()

    def setQss(self):
        qss = getStyleSheetFromFile(':/qss/qss/image.css')
        self.setStyleSheet(qss)

    def on_bottomToolsView_menued_clicked(self):
        if self.imagePager.isVisible():
            self.imagePager.hide()
        else:
            self.imagePager.show()

    def on_fullScreened_clicked(self):
        self.topToolsView.hide()
        self.bottomToolsView.hide()
        self.showFullScreen()

    def on_detailed_clicked(self):
        file = self.graphicsView.pixmap.fileName()
        if file is None:
            return
        self.pictureDetailsDialog = PictureDetailsDialog(self)
        self.pictureDetailsDialog.setFile(file)
        self.pictureDetailsDialog.show()

    def on_saveAsed_clicked(self):
        pixmap = self.graphicsView.pixmap
        if pixmap.fileName() is None:
            return
        time = datetime.now().strftime('%Y%m%d%H%M%S')
        file = QFileDialog.getSaveFileName(self, '保存文件', time, 'png(*.png);;jpg(*.jpg)')
        t = 'png'
        if file[0] == '':
            return
        if 'png' in file[1]:
            t = 'png'
        elif 'jpg' in file[1]:
            t = 'jpg'
        pixmap.save(file[0], t)

    def on_deleted_clicked(self):
        file = self.graphicsView.pixmap.fileName()
        if file is None:
            return
        if Path(file).is_file():
            send2trash([file])
            index = self.imageList.index(file)
            self.imageList.pop(index)
            self.imagePager.takeItem(index)
            item = self.imagePager.item(index)
            del item

    def on_setWallpapered_clicked(self):
        file = self.graphicsView.pixmap.fileName()
        if file is not None:
            jpg = Path(file).absolute()
            if jpg.is_file():
                windll.user32.SystemParametersInfoW(20, 0, str(jpg), 0)

    def on_imagePager_currentItemChanged(self, item: QListWidgetItem):
        if item is None:
            return
        file = item.toolTip()
        self.topToolsView.setText(Path(file).name)
        self.graphicsView.setImage(file)
        self.imagePos = self.imagePager.currentRow()
        self.imagePager.setImagePos(self.imagePos)
        self.imagePager.scrollToItem(item, QAbstractItemView.PositionAtCenter)
        self.NextAndLowerButtonHideOrShow()

    def keyPressEvent(self, a0: QKeyEvent):
        if a0.key() == Qt.Key_Escape:
            if self.isFullScreen():
                self.topToolsView.show()
                self.bottomToolsView.show()
                self.showNormal()

    def resizeEvent(self, event: QResizeEvent):
        self.lowerButton.move(self.graphicsView.pos())
        self.lowerButton.resize(50, self.graphicsView.height())
        self.nextButton.move(event.size().width() - 50, self.graphicsView.pos().y())
        self.nextButton.resize(50, self.graphicsView.height())
        super().resizeEvent(event)

    def NextAndLowerButtonHideOrShow(self):
        if len(self.imageList) <= 1:
            self.nextButton.hide()
            self.lowerButton.hide()
            return

        if self.imagePos == 0:
            self.lowerButton.hide()
            self.nextButton.show()
        elif self.imagePos == len(self.imageList) - 1:
            self.lowerButton.show()
            self.nextButton.hide()
        else:
            self.lowerButton.show()
            self.nextButton.show()

    def on_nextButton_clicked(self):
        self.imagePos += 1
        self.imagePager.setCurrentRow(self.imagePos)
        self.imagePager.setImagePos(self.imagePos)
        self.NextAndLowerButtonHideOrShow()

    def on_lowerButton_clicked(self):
        self.imagePos -= 1
        self.imagePager.setCurrentRow(self.imagePos)
        self.imagePager.setImagePos(self.imagePos)
        self.NextAndLowerButtonHideOrShow()

    def on_added_clicked(self):
        ii = ''
        for i in picture_type:
            ii += '*%s;' % i

        file = QFileDialog.getOpenFileName(self, '选择图片', './', f'图片文件({ii});;')[0]
        if file:
            self.setImage(file)
